package main.chapter6.basic

import main.chapter6.log
import java.io.ByteArrayOutputStream
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine

fun baseCoroutine(block: suspend () -> Unit) {
    block.startCoroutine(BaseContinuation())
}

suspend fun startDownloadImage(url: String) = suspendCoroutine<ByteArray> { continuation ->
    try {
        log("耗时操作，下载图片")
        val imgUrl = URL(url)
        //打开连接
        val urlConnection = imgUrl.openConnection()
        val inputStream = urlConnection.getInputStream()
        //将inputStream解析为Byte[]
        val output = ByteArrayOutputStream()
        val buffer = ByteArray(4096)
        while (true) {
            val result = inputStream.read(buffer)
            if (result == -1) {
                break
            } else {
                output.write(buffer, 0, result)
            }
        }
        if (output.toByteArray() != null) {
            //通过continuation将结果或者异常传递出去
            continuation.resume(output.toByteArray())
        } else {
            continuation.resumeWithException(Exception("图片请求异常"))
        }
    } catch (e: Exception) {
        continuation.resumeWithException(e)
    }

}